<?php

class Custom_EventHandler_PreviewPictures {

	protected $_propertyFrom = null;
	protected $_propertyTo = null;
	protected $_options = array();

	function __construct($options) {
		if (isset($options['from']) && isset($options['to'])) {
			$this->setFrom($options['from']);
			$this->setTo($options['to']);
			unset($options['from']);
			unset($options['to']);

			$this->_options = $options;
		} else {
			trigger_error('Object params is empty', E_USER_ERROR);
		}
	}

	function setFrom($code) {
		$this->_propertyFrom = $code;
	}

	function setTo($code) {
		$this->_propertyTo = $code;
	}

	/**
	 * Делает превию к картинкам для свойства типа файл
	 * 
	 * @param  array $arFields
	 * @return boolean
	 */
	function onAfterSave(&$arFields) {
		//поля свойств
		$dbResult = CIBlockProperty::GetList(false, array('IBLOCK_ID' => $arFields['IBLOCK_ID'], 'PROPERTY_TYPE' => 'F'));
		$arProperties = Ebx_Project_Tools::db2Array($dbResult);
		$arProperties = Ebx_Project_Tools::transformArray($arProperties, 'CODE', 'ID');

		//исходные картинки
		$dbPictures = CIBlockElement::GetProperty($arFields['IBLOCK_ID'], $arFields['ID'], false, false, array('CODE' => $this->_propertyFrom));
		$arPictures = Ebx_Project_Tools::db2Array($dbPictures);
		$arPictures = Ebx_Project_Tools::transformArray($arPictures, 'PROPERTY_VALUE_ID', 'VALUE');

		//превиюшки
		$dbPreviewPictures = CIBlockElement::GetProperty($arFields['IBLOCK_ID'], $arFields['ID'], false, false, array('CODE' => $this->_propertyTo));
		$arPreviewPictures = Ebx_Project_Tools::db2Array($dbPreviewPictures);
		$arPreviewPictures = Ebx_Project_Tools::transformArray($arPreviewPictures, 'PROPERTY_VALUE_ID', 'VALUE');

		//изменяемые картинки
		$modifiedPictures = array();

		//удаляемые картинки
		$deletedPictures = array();

		//список картинок
		$listPictures = array();

		//обновление сохраненной картинки
		foreach ($arFields['PROPERTY_VALUES'][$arProperties[$this->_propertyFrom]] as $id => $params) {
			$id = (int)$id;
			if ($id > 0) {
				$listPictures[] = $id;

				if (empty($params['name'])) {
					if (isset($params['del']) && $params['del'] == 'Y') {
						$deletedPictures[] = $id;
					}
					continue;
				} elseif ($params['error'] == 0) {
					$modifiedPictures[] = $id;
				}

			} elseif (!empty($params['name'])) {
				$listPictures[] = false;
			}
		}

		for ($i = 0, $cnt = count($listPictures); $i < $cnt; $i++, next($arPictures), next($arPreviewPictures)) {

			$mode = false;

			if ($listPictures[$i] !== false) {
				$picPropId = $listPictures[$i];
			} else {
				$picPropId = key($arPictures);
			}
			
			$previewPicPropId = key($arPreviewPictures);
			$id = isset($arPictures[$picPropId]) ? $arPictures[$picPropId] : 0;

			if ($id == 0) {
				$mode = 'delete';
			} elseif (in_array($picPropId, $modifiedPictures)) {
				$mode = 'update';
			} elseif (in_array($picPropId, $deletedPictures)) {
				$mode = 'delete';
			} elseif (!$previewPicPropId) {
				$mode = 'add';
			}

			if ($mode) {

				$arFileParams = array();

				switch ($mode) {
					case 'delete':
						if ($previewPicPropId > 0) {
							$arFile["del"] = "Y";
							$arFile["MODULE_ID"] = "iblock";
							$arFileParams = array($previewPicPropId => array('VALUE' => $arFile));
						}
					break;

					case 'update':
					case 'add':
						$newFile = CFile::CopyFile($id);
						if (!$newFile) {
							return false;
						}
						$newFilePath = CFile::GetPath($newFile);

						$newFilePath = $_SERVER['DOCUMENT_ROOT'].$newFilePath;

						Ebx_HelperBroker::helper('imageResize', $newFilePath, array(
							'type' => isset($this->_options['resize_type']) ? $this->_options['resize_type'] : 'crop',
							'width' => 50,
							'height' => 50
						));

						$arFile = CFile::MakeFileArray($newFilePath);

						if ($mode == 'update' && $previewPicPropId > 0) {
							$arFile["del"] = "Y";
							$arFile["MODULE_ID"] = "iblock";
							$arFileParams = array($previewPicPropId => array('VALUE' => $arFile));

						} elseif ($mode == 'add') {
							$arFileParams = array('VALUE' => $arFile);
						}
					break;
				}

				if ($arFileParams) {
					CIBlockElement::setPropertyValueCode(
						$arFields['ID'],
						$arProperties[$this->_propertyTo],
						$arFileParams
					);
				}

			}
		}

		return true;

	}


}

?>